package org.asg.dis.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class JwtService {

    private static final String SECRET_KEY = "12345678123456781234567812345678";
    private final long EXPIRATION_TIME = 15 * 24 * 60 * 60 * 1000; // 15天

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String generateAndStoreToken(long userId, Claims claims) {
        System.out.println("next: actually build token");
        System.out.println("Claims content: " + claims);

        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setClaims(claims)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();

        storeToken(token, userId);
        System.out.println("token is" + token);
        return token;
    }
    public boolean validateToken(String token) {
        Claims claims = parseToken(token);

        if (claims.getExpiration().before(new Date())) {
            return false; // token 过期
        }

        String redisTokenKey = "token:" + token; // 生成 Redis key
        Boolean isTokenBlacklisted = redisTemplate.hasKey(redisTokenKey);

        return !Boolean.TRUE.equals(isTokenBlacklisted);
    }
    public static Claims parseToken(String token) {
        System.out.println("rrrrready to parse");

        try{
            System.out.println("ready to parse");
            System.out.println(token);

            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            System.out.println(claims);
            return claims;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void storeToken(String token, long userId) {
        redisTemplate.opsForValue().set("token:" + token, String.valueOf(userId), EXPIRATION_TIME, TimeUnit.MILLISECONDS);
        System.out.println("token stored!!!");
    }

    public void deleteToken(String token) {
        redisTemplate.delete("token:" + token);
    }


}
